package cn.wdm.basic.service.impl;

import cn.wdm.basic.constants.BaseConstant;
import cn.wdm.basic.dto.LoginDto;
import cn.wdm.basic.dto.WeChatDto;
import cn.wdm.basic.exception.BusinesExceprion;
import cn.wdm.basic.service.ILoginService;
import cn.wdm.basic.util.AjaxResult;
import cn.wdm.basic.util.HttpClientUtils;
import cn.wdm.basic.util.MD5Utils;
import cn.wdm.basic.util.StrUtils;
import cn.wdm.basic.util.jwt.JwtUtils;
import cn.wdm.basic.util.jwt.RsaUtils;
import cn.wdm.basic.util.jwt.loginResult;
import cn.wdm.system.domain.Menu;
import cn.wdm.system.mapper.MenuMapper;
import cn.wdm.system.mapper.PermissionMapper;
import cn.wdm.user.domain.Logininfo;
import cn.wdm.user.domain.User;
import cn.wdm.user.domain.Wxuser;
import cn.wdm.user.mapper.LogininfoMapper;
import cn.wdm.user.mapper.UserMapper;
import cn.wdm.user.mapper.WxuserMapper;
import cn.wdm.user.service.IWxuserService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;

    /**
     * 普通登录(员工登陆或者是用户登陆)
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(LoginDto dto)  {
        Integer type = dto.getType();
        String username = dto.getUsername();
        String password = dto.getPassword();
        //1.参数的非空校验
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)) {
            throw new BusinesExceprion("参数不能为空");
        }
        //2.查询账号是否存在
        Logininfo logininfo=logininfoMapper.loadByUsername(username,type);//当前用户的信息
        if (logininfo == null) {
            throw new BusinesExceprion("用户不存在，去注册吧！");
        }
        //3.比对账号密码是否错误
        String salt = logininfo.getSalt();
        String psw = MD5Utils.encrypByMd5(password + salt);
        if (!psw.equals(logininfo.getPassword())) {
            throw new BusinesExceprion("你输入的密码错误");
        }
        //登录成功后应该将当前的登录人信息logininfo和permission，menus。token是jwt字符串返回给前端。
        return loginSuccessHandler(logininfo);

        //4.将当前的用户存入到redis中
        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //密码正确 返回token 和logininfo回去。
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/
    }
    /**
     *三方微信扫码登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WeChatDto dto) {
        String code = dto.getCode();
        if (code == null) {
            throw new BusinesExceprion("参数不能为空！");
        }
        //通过code获取oppenid和token
        String getTokenUrl= BaseConstant.WeChatConstants.TOKEN_URL
                .replace("APPID",BaseConstant.WeChatConstants.APPID)
                .replace("SECRET",BaseConstant.WeChatConstants.SECRET)
                .replace("CODE",code);
        //返回是一个字符串 里面有token和oppenId
        String str = HttpClientUtils.httpGet(getTokenUrl);
        //将该str转为对象 获取返回来的token和openid;
        JSONObject obj = JSONObject.parseObject(str);
        String accessToken = obj.getString("access_token");
        String openId = obj.getString("openid");
        //3.根据openId去查询用户有没有绑定userId
        Wxuser wxuser=wxuserMapper.loadByOpenId(openId);
        //如果wxuser不为空，且它的绑定用户也不为空。就直接免密登录
        if (wxuser != null&&wxuser.getUserId()!=null) {
            //根据user中的logininfoid查出logininfo
            Logininfo logininfo=logininfoMapper.loadByUserId(wxuser.getUserId());
            return AjaxResult.me().setResultObj(loginSuccessHandler(logininfo));
            /*//将该登录信息存储redis
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,//对象要序列化
                    30,
                    TimeUnit.MINUTES
            );
            //4.2 返回token + logininfo
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //我们是高级技师，应该考虑到一些敏感信息不要返回给前端
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);
            return AjaxResult.me().setResultObj(map);*/
        }
        //4.当当前的用户满意绑定userid的时候 就应该跳到绑定的页面，进行绑定
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
    }
    @Override
    public AjaxResult bind(WeChatDto dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        String openId = dto.getOpenId();
        String accessToken = dto.getAccessToken();
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(password)||StringUtils.isEmpty(openId)||StringUtils.isEmpty(accessToken)) {
            throw new BusinesExceprion("参数不能为空");
        }
        //1.根据账号去查询用户是否存在
        User user = userMapper.loadByPhone(phone);
        //如果user存在直接绑定 如果不存在根据账号信息生成新的绑定
        Logininfo logininfo=null;
        if (user != null) {
            //不为空查到根据user查到logininfo 进行一个绑定
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }else{
            //不存在根据填的用户生成新的用户
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //3.发起请求 获取用户的基本信息
        String wxUserUrl = BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openId);
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
        //将返回的微信用户信息转为对
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        return AjaxResult.me().setResultObj(loginSuccessHandler(logininfo));
        //生成token
       /* String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,//对象要序列化
                30,
                TimeUnit.MINUTES
        );
        //4.2 返回token + logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //我们是高级技师，应该考虑到一些敏感信息不要返回给前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return AjaxResult.me().setResultObj(map);*/
    }

    /**
     * 登录成功后的处理逻辑
     * @param logininfo 当前的登录人信息
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        loginResult loginResult = new loginResult();
        loginResult.setLogininfo(logininfo);
        //判断当前是不是员工，是员工就直接放行，没有资源权限等。
        //如果是员工就需要查出当前员工的权限
        if (logininfo.getType()==0) {
            //登录成功后应该将当前的登录人信息logininfo和permission，menus。token是jwt字符串返回给前端
            //1.根据logininfo查找当前登录额所有按钮权限
            List<String> permissions = permissionMapper.findPermissionsByLogininfoId(logininfo.getId());
            //2.根据logininfo查找当前登录人的所有菜单权限
            List<Menu> menus=menuMapper.findMenusByLogininfoId(logininfo.getId());
            //3.将当前的信息转为jwt字符串
            loginResult.setPermissions(permissions);
            loginResult.setMenus(menus);
        }
        //私有钥匙加密 获取私钥 私钥加密
        //这一步是将loginResult对象加密变为jwt字符串
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.private").getFile());
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 30);
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwtStr);
        //我们是高级技师，应该考虑到一些敏感信息不要返回给前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        map.put("permissions",loginResult.getPermissions());
        map.put("menus",loginResult.getMenus());
        return map;
    }

    /**
     * 转换对象
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//注意：一定要手动设置type 前端用户注册  1
        return logininfo;
    }
    private User dto2User(WeChatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

}
